<template>
    <el-dialog title="二维码" v-model="openWithdrawQr" width="600px" append-to-body>
        <!-- <el-image :src="tinyCodeSrc"></el-image> -->
        <div v-if="openWithdrawQr">
            <canvas id="canvasWithdraw" :width="560" :height="560"></canvas>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template>
  
<script setup>
import { withdrawal } from "@/api/subject/subject";
import { getToken } from '@/utils/auth'
import { ElLoading } from "element-plus";
import QRCode from "qrcode";

const { proxy } = getCurrentInstance();

const openWithdrawQr = ref(false);
const tinyCodeSrc = ref(null);
const tiny_str = ref(null);
const data = ref(null);
// 打开弹窗
function open(row) {
    openWithdrawQr.value = true;
    tinyCodeSrc.value = null;
    data.value = row
    getQrcode();
}

// 暴露出去
defineExpose({
    open,
})


function cancel() {
    openWithdrawQr.value = false;
}


// 获取二维码
function getQrcode() {
    tiny_str.value =
        "https://opr.gtcharger.com?withdrawal=" + getToken();
    createRegQrcode();
}

// 生成二维码
function createRegQrcode() {
    QRCode.toDataURL(tiny_str.value, { errorCorrectionLevel: "H" })
        .then((url) => {
            tinyCodeSrc.value = url.replace(/[\r\n]/g, "");
        })
        .catch((err) => {
            ElNotification({
                message: "二维码生成错误" + err,
                type: "error",
            });
            return;
        });
    setTimeout(() => {
        drawRegQrcode();
    }, 100);
}

// 绘制二维码
function drawRegQrcode() {
    let canvas = document.getElementById("canvasWithdraw");
    let ctx = canvas.getContext("2d"); // 创建画布
    let img = new Image(); // 因为拿不到图片静态资源，所以创建图片标签
    img.setAttribute("crossOrigin", "anonymous"); // 解决图片跨域问题,也要放到赋值前，否贼大部分浏览器会报错
    img.src = tinyCodeSrc.value;
    // 加载图片
    img.onload = () => {
        // 绘制图片
        ctx.drawImage(img, 0, 0, 560, 560);
        // 合成图片
        let imgUrl = canvas.toDataURL("image/jpg");
        tinyCodeSrc.value = imgUrl;
    };
}

function submitForm() {
    let loadingInstance = ElLoading.service({
        lock: true,
        body: true,
        text: "正在处理",
        background: "rgba(0, 0, 0, 0.7)",
    });
    withdrawal(data.value).then((response) => {
        loadingInstance.close();
        cancel()
    }).catch((error) => {
        loadingInstance.close();
    });
}
</script>
    
<style scoped>
.tiny_qr {
    width: 4.8cm;
}
</style>